<?php


namespace app\user\controller;


use app\common\model\UserIncome;
use app\http\middleware\checkTTUserToken;
use app\user\model\TtUser;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\DecryptException;
use think\Controller;
use think\Exception;
use think\exception\PDOException;
use think\facade\Config;
use  think\facade\Request;
use app\user\model\User as UserModel;
use app\common\model\KuaishouApply;

class User extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkTTUserToken::class'
     ];

    //快手申请状态
    public function ks_process()
    {
        $user_id = Request::param('user_id');
        $applys= KuaishouApply::where('user_id',$user_id)->page(1,100)->select();

        $this->result($applys,200,'');
    }


    //获取微信专属的二维码
    public function wxQrcode()
    {
        $user_id = Request::param('user_id');

        $config = [
            'app_id' =>Config::get('miniprogram.wx.appid') ,
            'secret' => Config::get('miniprogram.wx.secret')
        ];

        $app = Factory::miniProgram($config);

        $scene= json_encode([
            'lv_1_id'=>$user_id
        ]) ;
        // $this->result($scene,200,'');

        //小程序发布之前会报错
        $response = $app->app_code->getUnlimit(base64_encode($scene), [
            'page'  => 'pages/index/index',
            'width' => 400,
        ]);

        $base64 = chunk_split(base64_encode($response));
//        $base64 = 'data:image/png;base64,' . $base64;
        $data = [
            'img' => $base64
        ];
        $this->result($data,200,'');

    }

    //绑定推荐人
    public function bindPromoter()
    {
        $user_id = Request::param('user_id');
        $lv_1_id=Request::param('lv_1_id',0);

        $user=UserModel::get($user_id);

        //不能自己绑定自己
        if($user_id>=$lv_1_id){
            $this->result(null,200,'不能自己绑定自己');
        }

        //已经绑定过了，或者需要绑定的和传参相同，都不做更改
        if($user->lv_1_id!=0){
            $this->result('',400,'已经绑定过推荐人了');
        }else{
            //推荐人的资料
            $lv_1_info=UserModel::get($lv_1_id);

            if($lv_1_info){
                $user->lv_1_id=$lv_1_id;
                $user->lv_2_id=$lv_1_info->lv_1_id;
                $res=  $user->save();

                if($res){
                    $this->result('',200,'绑定成功');
                }else{
                    $this->result('',400,'绑定失败');
                }
            }else{
                $this->result('',400,'推荐人不合法');
            }
        }
    }

    //用户信息
    public function info()
    {
        $user_id = Request::param('user_id');
        $info = \app\user\model\User::get($user_id);

        //判断是否存在该用户
        if ($info) {
            $info['wallet']=UserIncome::wallet($user_id);
            $this->result($info, 200, '获取用户资料成功');
        } else {
            $this->result(null, 300, '该用户不存在，请重新登录');
        }
    }

    //抖音二维码
    public function dyShareQrcode()
    {
        $url = "https://developer.toutiao.com/api/apps/qrcode";
        $path = Request::param('path');
        $mini_app_code = Request::param('mini_app_code',0);

        $product_id = Request::param('product_id',0);           //为0的时候表示直接跳转到小程序

        $send = [
            'access_token' => $this->getAccessToken(),
            'appname' => 'douyin',
            'path' => urlencode($path),
//            'path'=>'pages/menu/menu?id=1',
        ];
        $send = json_encode($send);

        //请求字节跳动，post获取小程序二维码
        $resWxQrCode = $this->curlPost($url, $send);
        $base64 = chunk_split(base64_encode($resWxQrCode));
        // 输出
//        $encode = '<img src="data:image/jpg/png/gif;base64,' . $base64 .'" >';
        $base64 = 'data:image/png;base64,' . $base64;
        $data = [
            'img' => $base64,
            'path' => urlencode($path)
        ];
        $this->result($data, 200, '成功');

//        $this->result($resWxQrCode);
    }

    //注意：提交格式为json
    protected function curlPost($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER,
                array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //获取抖音小程序的AccessToken
    private function getAccessToken()
    {
        $appid = Config::get('miniprogram.tt.appid');
        //appid
        $appsecret =Config::get('miniprogram.tt.secret');
        //app secret
        $url = "https://developer.toutiao.com/api/apps/token?appid=" . $appid . "&secret=" . $appsecret . "&grant_type=client_credential";
        //get提交
        $access_token = $this->curlRequest($url);
        $access_token = json_decode($access_token, true);
        return $access_token['access_token'];
    }

    public function curlRequest($url, $data = null, $type = 1)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            if ($type == 2) {
                curl_setopt($curl, CURLOPT_HTTPHEADER,
                    array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
            }
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    //更新用户资料
    public function update()
    {
        $data = Request::only(['user_id' => '', 'nickName' => '', 'gender' => '', 'city' => '', 'province' => '', 'avatarUrl' => '', 'wechat' => '']);

        $update = [
            'username' => $data['nickName'],
            'gender' => $data['gender'],
            'avatar' => $data['avatarUrl'],
            'wechat' => $data['wechat']
        ];

        //去掉空数组
        foreach ($update as $k => $v) {
            if ($v === '')
                unset($update[$k]);
        }

        try {
            $res = \app\user\model\User::where(['id' => $data['user_id']])->update($update);
            $this->result($res, 200, '资料更新成功');
        } catch (PDOException $e) {
            setLog("user_error",$e->getMessage());
            setLog("user_error2",$e->getTraceAsString());
            $this->result($e->getMessage(), 400, '资料更新失败');
        } catch (Exception $e) {
            setLog("user_error",$e->getMessage());
            setLog("user_error2",$e->getTraceAsString());
            $this->result($e->getMessage(), 400, '资料更新失败');
        }
    }

    //微信用户绑定手机号
    public function wxBindMobile($code, $iv, $encryptedData, $user_id)
    {
        $config = [
            'app_id' => Config::get('miniprogram.wx.appid'),
            'secret' => Config::get('miniprogram.wx.secret'),
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array'
        ];

        $app = Factory::miniProgram($config);

        $res = $app->auth->session($code);

        $session_key = $res['session_key'];
        $openid = $res['openid'];

        try {
            $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);

            //解密成功之后，直接修改数据库
            $res2 = \app\user\model\User::where(['id' => $user_id])->update([
                'mobile' => $decryptedData['phoneNumber']
            ]);
            //手机号绑定成功
            $this->result(['mobile' => $decryptedData['phoneNumber']], 200, '绑定成功');
        } catch (DecryptException $e) {
            $this->result('', 400, '绑定失败，请再试一次');
        }

    }

    //解密出微信用户的资料
    public function get_wx_user_info($code, $iv, $encryptedData)
    {

        $config = [
            'app_id' => Config::get('miniprogram.wx.appid'),
            'secret' => Config::get('miniprogram.wx.secret'),
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array'
        ];

        $app = Factory::miniProgram($config);

        $res = $app->auth->session($code);

        $session_key = $res['session_key'];
        $openid = $res['openid'];

        try {
            $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);
        } catch (DecryptException $e) {
            $this->result(null, 200, '解密失败');
        }

        $this->result($decryptedData, 200, '解密过后的资料');
    }

}
